import random
import string
import io

from afast_core.core_libs.captcha.image import ImageCaptcha, random_color


def generate_captcha( width=170, height=60 ,font_sizes=(25, 23, 27)):
    # # 返回大写字母
    # uppercase = string.ascii_uppercase
    # # 返回小写字母
    # lowercase = string.ascii_lowercase
    # 返回大小写字母
    letters = string.ascii_letters
    # 返回数字
    digits = string.digits

    # 随机选取 4 个字符
    random_str = ''.join([random.choice(digits + letters) for j in range(4)])

    width, height = width, height
    # fonts = ['ariblk.ttf',]
    # 创建图片生成器
    generator = ImageCaptcha(width=width,height=height,font_sizes=font_sizes)

    # 创建验证码图片
    # img = generator.create_captcha_image(chars=random_str, color=random_color(1, 255), background=random_color(1, 255))random_color(100, 255)
    img = generator.create_captcha_image(chars=random_str, color=random_color(1, 255), background=(255,255,255))

    # 为图片增加干扰点
    generator.create_noise_dots(img, random_color(1, 255))
    # 为图片增加干扰线
    generator.create_noise_curve(img, random_color(1, 255))

    # 展示图片（展示图片的操作与上面保不保存无关）
    # img.show()

    # # 保存生成的图片到本地
    # fileName = "saveImg"
    # if not os.path.exists(fileName):
    #     os.mkdir(fileName)
    # img.save("%s/%s.png" % (fileName, random_str))

    # 将图片保存到缓存中
    buffer = io.BytesIO()
    img.save(buffer, 'PNG')
    # 读取图片的byte值
    image_data = buffer.getvalue()
    buffer.close()

    return random_str, image_data


import base64


def encode_base64(file):
    with open(file, 'rb') as f:
        img_data = f.read()
        base64_data = base64.b64encode(img_data)
        # print(base64_data)
        # 如果想要在浏览器上访问base64格式图片，需要在前面加上：data:image/jpeg;base64,
        base64_str = str(base64_data, 'utf-8')
        return base64_data


def decode_base64(base64_data):
    with open('./images/base64.jpg', 'wb') as file:
        img = base64.b64decode(base64_data)
        file.write(img)


if __name__ == '__main__':
    pass
    # # @loginrouter.get('/sys/randomImage/1629428467008',summary="获取随机图形验证码")
    # # async def get_routine_list_router():
    # #     # 生成验证码
    # #     random_str, image_data = generate_captcha(width=100, height=35)
    # #     base64_data = str(base64.b64encode(image_data), "utf-8")  # 使用base64进行加密
    # #     request.session["session_code"] = random_str.lower()
    # #     print("写入的验证码：", random_str)
    # #     return ApiResponse(result=f"data:image/jpg;base64,{base64_data}", message='')
